package com.kdx.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kdx.wallet.entity.Record;
import com.kdx.wallet.entity.User;
import com.kdx.wallet.entity.Wallet;
import com.kdx.wallet.mapper.RecordMapper;
import com.kdx.wallet.mapper.UserMapper;
import com.kdx.wallet.mapper.WalletMapper;
import com.kdx.wallet.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private WalletMapper walletMapper;

    /**
     * 创建用户并绑定钱包
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User register(String username) {
        User user = new User();
        user.setUsername(username);
        save(user);
        Wallet wallet = new Wallet();
        wallet.setUserId(user.getId());
        walletMapper.insert(wallet);
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("wallet_id", wallet.getId()).eq("id", user.getId());
        update(wrapper);
        return user;
    }

    @Override
    public User getUserByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return getOne(wrapper);
    }

}
